package imagekeeper.data;

import java.util.ArrayList;
import java.util.Iterator;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import imagekeeper.dmi.Image;
import imagekeeper.dmi.ImageTag;
import imagekeeper.dmi.ImageTagManager;
import imagekeeper.data.mapping.ImageTagMapper;


class ImageTagManagerImpl extends AbstractEntityManager implements ImageTagManager {
    public ImageTagManagerImpl(DataSource ds) {
        dataSource = ds;
    }

    @Override
    public void create(Object newTag) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    public void create(Image img, Connection con) throws SQLException {
        SqlStatementCreateImageTag sqlSt = null;
        Iterator<ImageTag> tagsIterator = img.getTags().iterator();
        try {
            sqlSt = new SqlStatementCreateImageTag(con);
            while (tagsIterator.hasNext()) {
                ImageTag tag = tagsIterator.next();
                sqlSt.setTagValue(tag.getValue());
                sqlSt.setImageId(img.getId());
                sqlSt.executeUpdate();
                sqlSt.clearParameters();
            }
        }
        catch (SQLException ex) {
            throw ex;
        }
        finally {
            if (sqlSt != null) sqlSt.close();
        }
    }

    @Override
    public void remove(Object tag) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void refresh(Object tag) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    @Override
    public void lookUpImageTags(Image img) throws SQLException {
        SqlStatementSelectImageTags sqlSt = null;
        Connection con = null;
        try {
            con = dataSource.getConnection();
            con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            sqlSt = new SqlStatementSelectImageTags(con, img.getId());
            ResultSet rs = sqlSt.executeQuery();
            ArrayList<ImageTag> tagList = ImageTagMapper.getImageTags(rs);
            img.getTags().addAll(tagList);
        }
        catch (SQLException ex) {
            throw ex;
        }
        finally {
            if (sqlSt != null) sqlSt.close();
            if (con != null) closeConnection(con);
        }
    }
    
    public void updateImageTags(Image img, Connection con) throws SQLException {
        SqlStatementRemoveImageTags sqlStRemoveImgTags = null;
        try {
            sqlStRemoveImgTags = new SqlStatementRemoveImageTags(con, img.getId());
            sqlStRemoveImgTags.executeUpdate();
            this.create(img, con);
        }
        catch (SQLException ex) {
            throw ex;
        }
        finally {
            if (sqlStRemoveImgTags != null) sqlStRemoveImgTags.close();
        }
    } 
}
